<template>
  <div >
      <n-card size="small" class="column-card-left shadow-card">
          <template #header>
              <div style="display: flex; flex-direction: row; align-items: center">
                  <span>指标看板</span>
                  <icon-ic:baseline-keyboard-arrow-right style="margin-left: 5px;"/> <!-- 使用 Font Awesome 图标库作为示例 -->
              </div>
          </template>
        <template #header-extra>
          更新至 {{currentTime}}（站点时间）
        </template>
          <n-flex justify="space-between">
              <n-flex vertical>
                  <span>销售量（个）</span>
                  <span>{{saleAmount}}</span>
                  <span>昨 {{saleAmountYesterday}}</span>
              </n-flex>
              <n-flex vertical>
                  <span>销售额（元）</span>
                  <span>{{saleMoney}}</span>
                  <span>昨 {{saleMoneyYesterday}}</span>
              </n-flex>
              <n-flex vertical>
                  <span>销售利润（元）</span>
                  <span>{{saleProfit}}</span>
                  <span>昨 {{saleProfitYesterday}}</span>
              </n-flex>
              <n-flex vertical>
                  <span>成本价（元）</span>
                  <span>{{saleCost}}</span>
                  <span>昨 {{saleCostYesterday}}</span>
              </n-flex>
              <n-flex vertical>
                  <span>物流费（元）</span>
                  <span>{{logisticProviderCost}}</span>
                  <span>昨 {{logisticProviderCostYesterday}}</span>
              </n-flex>
          </n-flex>
          <div ref="option1Container" style="width: 95%; height: 300px; margin-left: 10px; margin-top: 40px;"></div>
      </n-card>
      <div style="width: 100%; flex-direction: row; display: flex; justify-content: space-evenly">
          <n-card size="small" class="second-column-card second-column-card-left shadow-card">
              <template #header>
                  <div style="display: flex; flex-direction: row; align-items: center">
                      <span>订单分析</span>
                      <icon-ic:baseline-keyboard-arrow-right style="margin-left: 5px;"/> <!-- 使用 Font Awesome 图标库作为示例 -->
                  </div>
              </template>
              <template #header-extra>
                  <n-radio-group value="quantity" size="small">
                      <n-radio-button
                          class="left-button"
                          value="quantity"
                          label="订单状态"
                      />
                      <n-radio-button
                          class="right-button"
                          value="currency"
                          label="订单类型"
                      />
                  </n-radio-group>
              </template>
              <div style="display: flex; flex-direction: row; justify-content: space-evenly">
                  <div style="width: 48%;">
                      <div ref="option2Container" style="width: 90%; height: 300px; margin-left: 10px;"></div>
                  </div>
                  <div style="width: 48%;">
                      <div ref="option3Container" style="width: 90%; height: 300px; margin-left: 10px;"></div>
                  </div>
              </div>
          </n-card>
          <n-card size="small" class="second-column-card second-column-card-right shadow-card">
              <template #header>
                  <div style="display: flex; flex-direction: row; align-items: center">
                      <span>站点销售总览</span>
                      <icon-ic:baseline-keyboard-arrow-right style="margin-left: 5px;"/> <!-- 使用 Font Awesome 图标库作为示例 -->
                  </div>
              </template>
            <template #header-extra>
              更新至 {{currentTime}}（站点时间）
            </template>
            <n-data-table
                remote
                :single-line="false"
                ref="table"
                :columns="columns"
                :data="staticsList"
                :loading="loading"
                :max-height="250"
            />
          </n-card>
      </div>
      <div style="width: 100%; flex-direction: row; display: flex; justify-content: space-evenly">
          <n-card size="small" class="second-column-card second-column-card-left shadow-card">
              <template #header>
                  <div style="display: flex; flex-direction: row; align-items: center">
                      <span>店铺销售量分析</span>
                      <icon-ic:baseline-keyboard-arrow-right style="margin-left: 5px;"/> <!-- 使用 Font Awesome 图标库作为示例 -->
                  </div>
              </template>
            <template #header-extra>
              更新至 {{currentTime}}（站点时间）
            </template>
              <div ref="option4Container" style="width: 90%; height: 300px; margin-left: 10px;"></div>
          </n-card>
          <n-card size="small" class="second-column-card second-column-card-right shadow-card">
              <template #header>
                  <div style="display: flex; flex-direction: row; align-items: center">
                      <span>店铺销售额分析</span>
                      <icon-ic:baseline-keyboard-arrow-right style="margin-left: 5px;"/> <!-- 使用 Font Awesome 图标库作为示例 -->
                  </div>
              </template>
            <template #header-extra>
              更新至 {{currentTime}}（站点时间）
            </template>
              <div ref="option7Container" style="height: 300px; margin-left: 10px;"></div>
          </n-card>
      </div>
      <div style="width: 100%; flex-direction: row; display: flex; justify-content: space-evenly">
          <n-card size="small" class="third-column-card third-column-card-left shadow-card">
              <template #header>
                  <div style="display: flex; flex-direction: row; align-items: center">
                      <span>仓库统计</span>
                      <icon-ic:baseline-keyboard-arrow-right style="margin-left: 5px;"/> <!-- 使用 Font Awesome 图标库作为示例 -->
                  </div>
              </template>
            <template #header-extra>
              更新至 {{currentTime}}（站点时间）
            </template>
              <n-table :single-line="false" style="margin-top: 5px; font-size: 13px;">
                  <thead>
                  <tr>
                      <th class="th-left">仓库类型</th>
                      <th class="th-left">库存量</th>
                      <th class="th-left">销售量</th>
                      <th class="th-left">销售额</th>
                  </tr>
                  </thead>
                  <tbody>
                  <tr>
                      <td class="table-with-icon">
                          本地仓
                      </td>
                      <td>{{amountInLocal}}</td>
                      <td>{{saleAmountInLocal}}</td>
                      <td>{{saleMoneyInLocal}}</td>
                  </tr>
                  <tr>
                      <td class="table-with-icon">
                          海外仓
                      </td>
                      <td>{{amountInOversee}}</td>
                      <td>{{saleAmountInOversee}}</td>
                      <td>{{saleMoneyInOversee}}</td>
                  </tr>
                  <tr>
                    <td class="table-with-icon">
                      平台仓
                    </td>
                    <td>{{amountInPlatform}}</td>
                    <td>{{saleAmountInPlatform}}</td>
                    <td>{{saleMoneyInPlatform}}</td>
                  </tr>
                  <tr style="background-color: #005bf5">
                      <th  class="table-with-icon th-left">合计</th>
                      <th  class="th-left">{{amountInLocal+amountInOversee+amountInPlatform}}</th>
                      <th  class="th-left">{{saleAmountInPlatform+saleAmountInOversee+saleAmountInLocal}}</th>
                      <th  class="th-left">{{saleMoneyInOversee+saleMoneyInPlatform+saleMoneyInLocal}}</th>
                  </tr>
                  </tbody>
              </n-table>
          </n-card>
          <n-card size="small" class="third-column-card third-column-card-right shadow-card">
              <template #header>
                  <div style="display: flex; flex-direction: row; align-items: center">
                      <span>商品品类销售分析</span>
                      <icon-ic:baseline-keyboard-arrow-right/> <!-- 使用 Font Awesome 图标库作为示例 -->
                  </div>
              </template>
            <template #header-extra>
              <n-button>{{ date }}</n-button>
            </template>
              <div style="display: flex; flex-direction: row; justify-content: space-evenly">
                  <div style="width: 48%;">
                      <div ref="option5Container" style="width: 100%; height: 250px; margin-left: 10px;"></div>
                  </div>
                  <div style="width: 48%;">
                      <n-table :bordered="false">
                          <thead>
                          <tr>
                              <th>畅销榜Top4</th>
                              <th>销售额</th>
                              <th>销售额占比</th>
                          </tr>
                          </thead>
                          <tbody>
                          <tr>
                              <td>{{sortCategory1}}</td>
                              <td>{{sortSaleMoney1}}</td>
                              <td>{{sortMoney1}}</td>
                          </tr>
                          <tr>
                              <td>{{sortCategory2}}</td>
                              <td>{{sortSaleMoney2}}</td>
                              <td>{{sortMoney2}}</td>
                          </tr>
                          <tr>
                              <td>{{sortCategory3}}</td>
                              <td>{{sortSaleMoney3}}</td>
                              <td>{{sortMoney3}}</td>
                          </tr>
                          <tr>
                              <td>{{sortCategory4}}</td>
                              <td>{{sortSaleMoney4  }}</td>
                              <td>{{sortMoney4}}</td>
                          </tr>
                          </tbody>
                      </n-table>
                  </div>
              </div>
          </n-card>
      </div>
      <n-card size="small" class="column-card-left shadow-card">
          <template #header>
              <div style="display: flex; flex-direction: row; align-items: center">
                  <span>商品实时销量</span>
                  <icon-ic:baseline-keyboard-arrow-right style="margin-left: 5px;"/> <!-- 使用 Font Awesome 图标库作为示例 -->
              </div>
          </template>

          <div ref="option6Container" style="width: 100%; height:350px; margin-left: 10px; margin-top: 40px;"></div>
      </n-card>
  </div>
</template>

<script setup>
import {h, onMounted, reactive, ref} from 'vue'
import * as echarts from 'echarts'
import api from "@/api/admin.js";

const currentTime = ref(getCurrentFormattedDateTime());
function getCurrentYearAndWeekNumberWithDay() {
  let now = new Date();
  let year = now.getFullYear();
  let dayOfYear = getDayOfYear(now);
  let dayOfWeek = now.getDay();
  if (dayOfYear < (1 + (7 - dayOfWeek))) {
    year--;
    dayOfYear += 365 + ((year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 1 : 0); // 加上上一年的天数，考虑闰年
  }
  let weekNumber = Math.ceil((dayOfYear + 7 - dayOfWeek) / 7);
  let weekDays = ['日', '一', '二', '三', '四', '五', '六'];
  let weekDayCN = weekDays[dayOfWeek];
  return `${year}年第${weekNumber}周 周${weekDayCN}`;
}
function getDayOfYear(date) {
  let start = new Date(date.getUTCFullYear(), 0, 0);
  let diff = date - start + ((start.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000);
  let oneDay = 1000 * 60 * 60 * 24;
  return Math.floor(diff / oneDay);
}
const date = ref(getCurrentYearAndWeekNumberWithDay())
// 近一周销售量
const saleAmountInWeek = ref(null)
// 近一周销售额
const saleMoneyInWeek = ref(null)
// 近一周销售利润
const saleProfitInWeek = ref(null)
// 近一周成本价
const totalCostInWeek = ref(null)
// 近一周物流费
const logisticsProviderCostInWeek = ref(null)

const option1Container = ref(null)
let option1Chart = null
const defaultEmptyList = [0,0,0,0,0,0,0]
const option1  = ref({
    title: {
        text: '销售数据'
    },
    tooltip: {
        trigger: 'axis'
    },
    legend: {
        data: ['销售量', '销售额', '销售利润', '成本价', '物流费']
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    toolbox: {
        feature: {
            saveAsImage: {}
        }
    },
    xAxis: {
        type: 'category',
        boundaryGap: false,
        data: getLastSevenDays()
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            name: '销售量（个）',
            type: 'line',
            data: defaultEmptyList
        },
        {
            name: '销售额（元）',
            type: 'line',
            data: defaultEmptyList
        },
        {
            name: '销售利润（元）',
            type: 'line',
            data: defaultEmptyList
        },
        {
            name: '成本价（元）',
            type: 'line',
            data: defaultEmptyList
        },
        {
            name: '物流费（元）',
            type: 'line',
            data: defaultEmptyList
        }
    ]
});

const option2Container = ref(null)
let option2Chart = null
const option2 = ref({
    tooltip: {
        trigger: 'item'
    },
    legend: {
        top: '5%',
        left: 'center'
    },
    series: [
        {
            name: '该状态下客户订单数（单）',
            type: 'pie',
            radius: ['40%', '80%'],
            avoidLabelOverlap: false,
            label: {
                show: false,
                position: 'center'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: 40,
                    fontWeight: 'bold'
                }
            },
            labelLine: {
                show: false
            },
            data: []
        }
    ]
})

const option3Container = ref(null)
let option3Chart = null
const option3 = ref({
        tooltip: {
            trigger: 'item'
        },
        legend: {
            top: '5%',
            left: 'center',

        },
        series: [
            {
                name: '该类型的订单总金额（元）',
                type: 'pie',
                radius: ['40%', '80%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 40,
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: []
            }
        ]
    })

const option4Container = ref(null)
let option4Chart = null
// prettier-ignore
let dataAxis = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
// prettier-ignore
let data = [12.3, 9.4, 11.4, 14.0, 8.5,7.2,10.3,8.3,11.5,10.7,8.3,7.9];
let yMax = 500;
let dataShadow = [];
for (let i = 0; i < data.length; i++) {
    dataShadow.push(yMax);
}
const option4 = ref({
    tooltip: {
        trigger: 'item',
    },
    title: {
        text: '店铺商品销售总量（个）',
    },
    xAxis: {
        data: [],
        axisLabel: {
            inside: true,
            color: '#fff'
        },
        axisTick: {
            show: false
        },
        axisLine: {
            show: false
        },
        z: 10
    },
    yAxis: {
        axisLine: {
            show: false
        },
        axisTick: {
            show: false
        },
        axisLabel: {
            color: '#999'
        }
    },
    dataZoom: [
        {
            type: 'inside'
        }
    ],
    series: [
        {
            type: 'bar',
            showBackground: true,
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#83bff6' },
                    { offset: 0.5, color: '#188df0' },
                    { offset: 1, color: '#188df0' }
                ])
            },
            emphasis: {
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#2378f7' },
                        { offset: 0.7, color: '#2378f7' },
                        { offset: 1, color: '#83bff6' }
                    ])
                }
            },
            data: []
        }
    ]
});
// Enable data zoom when user click bar.
const zoomSize = 6;

const option5Container = ref(null)
let option5Chart = null
const option5 = ref({
    tooltip: {
        trigger: 'item',
    },
    legend: {
        top: '5%',
        left: 'center'
    },
    series: [
    {
        name: '该类商品的总销售额（元）',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
        },
        label: {
            show: false,
            position: 'center',
        },
        emphasis: {
            label: {
                show: true,
                fontSize: 40,
                fontWeight: 'bold'
            }
        },
        labelLine: {
            show: false
        },
      data: []
    }
  ]
})

const option6Container = ref(null)
let option6Chart = null
const dataList = ref([]);
for (let i = 0; i < 5; ++i) {
    dataList.value.push(Math.round(Math.random() * 300));
}
const option6 = ref({
    tooltip: {
        trigger: 'item',
    },
    xAxis: {
        max: 'dataMax'
    },
    yAxis: {
        type: 'category',
        data: [],
        inverse: true,
        animationDuration: 300,
        animationDurationUpdate: 300,
        max: 4 // only the largest 3 bars will be displayed
    },
    series: [
        {
            realtimeSort: true,
            name: '商品实时总销量（个）',
            type: 'bar',
            data: [],
            label: {
                show: true,
                position: 'right',
                valueAnimation: true
            }
        }
    ],
    legend: {
        show: true
    },
    animationDuration: 0,
    animationDurationUpdate: 3000,
    animationEasing: 'linear',
    animationEasingUpdate: 'linear'
});

//商品销售实时
const saleAmountList=ref([])
const querySaleAmountList = async () => {
  loading.value = true
  try {
    const res = await api.getSaleAmountByStoreCommodity()
    if(res.code === 200) {
      res.data.map((item,i)=>{
        saleAmountList.value.push({
          name:item.productName,
          value:item.saleAmount,
        })
      })
      console.log("saleAmountList:")
      console.log(saleAmountList.value)
    }
    else {
      $message.error(res.message)
    }
    option6.value.series[0].data=saleAmountList.value
    const newArray = saleAmountList.value.map(item => item.name);
    option6.value.yAxis.data=newArray
    console.log("option6")
    console.log(option6.value.series[0].data)
  } catch (err) {
    $message.error("获取国家信息失败！")
  }finally{
    loading.value = false
  }
}

const option7Container = ref(null)
let option7Chart = null
const option7 = ref({
    title: {
        text: '店铺销售额（元）'
    },
    tooltip: {
        trigger: 'item',
    },
    toolbox: {
        feature: {
            dataView: { readOnly: false },
            restore: {},
            saveAsImage: {}
        }
    },
    series: [
        {
            name: '店铺销售额',
            type: 'funnel',
            left: '10%',
            top: 60,
            bottom: 60,
            width: '80%',
            min: 0,
            max: 100,
            minSize: '0%',
            maxSize: '100%',
            sort: 'descending',
            gap: 2,
            label: {
                show: true,
                position: 'inside',
            },
            tooltip: {
                trigger: 'item',
            },
            labelLine: {
                length: 10,
                lineStyle: {
                    width: 1,
                    type: 'solid'
                }
            },
            itemStyle: {
                borderColor: '#fff',
                borderWidth: 1
            },
            emphasis: {
                label: {
                    fontSize: 20
                }
            },
            data: []
        }
    ]
});

let total = 0
const nationList=ref([])
const staticsList=ref([])
const loading = ref(true)
const columns =[
  {
    key:'colId',
    title:'序号',
    width:30,
  },
  {
    key:'nation',
    title:'站点',
    width:30,
  },
  {
    key:'saleAmount',
    title:'销量（个）',
    width:30,
  },
  {
    key:'saleMoney',
    title:'销售额（元）',
    width:30,
  },
  {
    key:'saleProfit',
    title:'利润（元）',
    width:30,
  }
]
const queryNationList = async () => {
  loading.value = true
  try {
    const res = await api.getNation()
    if(res.code === 200) {
      res.data.map((item,i)=>{
        nationList.value.push({
          nation: item,
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取国家信息失败！")
  }finally{
    loading.value = false
  }
}
const queryStaticsList = async () => {
  loading.value = true
  try{
    let colId=1
    for (let nation of nationList.value){
      const res=await api.getSaleMoneyByNation({
          params: {
              nation: nation.nation
          }
      })
      const res1=await api.getSaleAmountByNation(
        {params:{
          nation:nation.nation
        }})
      const res2=await api.getSaleProfitByNation(
        {params:{
            nation:nation.nation
          }})
      if(res.code===200)
      {
        staticsList.value.push ({
          colId:colId,
          saleAmount: res1.data,
          nation: nation.nation,
          saleMoney:  res.data,
          saleProfit:res2.data,
        });
      }else {
        $message.error(res.message)
      }
      colId+=1
  }

  }catch (err){
    $message.error("统计数据失败！")
  }finally{
    loading.value = false
  }
}

const saleAmount = ref(0)
const saleMoney=ref(0)
const saleProfit=ref(0)
const saleCost=ref(0)
const logisticProviderCost=ref(0)

const saleAmountYesterday = ref(0)
const saleMoneyYesterday=ref(0)
const saleProfitYesterday=ref(0)
const saleCostYesterday=ref(0)
const logisticProviderCostYesterday=ref(0)
const querySaleAmount = async () => {
    try {
        const res = await api.getSaleAmount()
        if(res.code === 200) {
            saleAmount.value = res.data
        }
    } catch (err) {
        $message.error("获取销售量失败！")
    }
}
const querySaleAmountYesterday = async () => {
    try {
        const res = await api.getSaleAmountInYesterday()
        if(res.code === 200) {
            saleAmountYesterday.value = res.data
        }
    } catch (err) {
        $message.error("获取销售量失败！")
    }
}

const querySaleMoney = async () => {
  try {
    const res = await api.getSaleMoney()
    if(res.code === 200) {
      saleMoney.value = res.data
    }
  } catch (err) {
    $message.error("获取销售额失败！")
  }
}
const querySaleMoneyYesterday = async () => {
    try {
        const res = await api.getSaleMoneyYesterday()
        if(res.code === 200) {
            saleMoneyYesterday.value = res.data
        }
    } catch (err) {
        $message.error("获取销售额失败！")
    }
}

const querySaleProfit = async () => {
  try {
    const res = await api.getSaleProfit()
    if(res.code === 200) {
      saleProfit.value = res.data
    }
  } catch (err) {
    $message.error("获取毛利润失败！")
  }
}
const querySaleProfitYesterday = async () => {
    try {
        const res = await api.getSaleProfitYesterday()
        if(res.code === 200) {
            saleProfitYesterday.value = res.data
        }
    } catch (err) {
        $message.error("获取毛利润失败！")
    }
}

const querySaleCost = async () => {
  try {
    const res = await api.getSaleCost()
    if(res.code === 200) {
      saleCost.value = res.data
    }
  } catch (err) {
    $message.error("获取毛利润失败！")
  }
}
const querySaleCostYesterday = async () => {
    try {
        const res = await api.getSaleCostYesterday()
        if(res.code === 200) {
            saleCostYesterday.value = res.data
        }
    } catch (err) {
        $message.error("获取毛利润失败！")
    }
}

const queryLogisticProviderCost = async () => {
  try {
    const res = await api.getLogisticProviderCost()
    if(res.code === 200) {
      logisticProviderCost.value = res.data
    }
  } catch (err) {
    $message.error("获取毛利润失败！")
  }
}
const queryLogisticProviderCostYesterday = async () => {
    try {
        const res = await api.getLogisticProviderCostYesterday()
        if(res.code === 200) {
            logisticProviderCostYesterday.value = res.data
        }
    } catch (err) {
        $message.error("获取毛利润失败！")
    }
}

//仓库统计
const amountInLocal=ref(0)
const amountInOversee=ref(0)
const amountInPlatform=ref(0)
const queryAmountInLocal=async ()=>{
  try {
    const res = await api.findStoreCommodityByType(
      {
        params:{
          type:'本地仓'
        }
      }
    )
    if(res.code === 200) {
      amountInLocal.value = res.data
    }
  } catch (err) {
    $message.error("获取本地仓库存失败！")
  }
}
const queryAmountInOversee=async ()=>{
  try {
    const res = await api.findStoreCommodityByType(
      {
        params:{
          type:'海外仓'
        }
      }
    )
    if(res.code === 200) {
      amountInOversee.value = res.data
    }
  } catch (err) {
    $message.error("获取本地仓库存失败！")
  }
}
const queryAmountInPlatform=async ()=>{
  try {
    const res = await api.findStoreCommodityByType(
      {
        params:{
          type:'平台仓'
        }
      }
    )
    if(res.code === 200) {
      amountInPlatform.value = res.data
    }
  } catch (err) {
    $message.error("获取本地仓库存失败！")
  }
}

const saleAmountInLocal=ref(0)
const saleAmountInOversee=ref(0)
const saleAmountInPlatform=ref(0)
const querySaleAmountInLocal=async ()=>{
  try {
    const res = await api.getSaleAmountByStoreType(
      {
        params:{
          type:'本地仓'
        }
      }
    )
    if(res.code === 200) {
      saleAmountInLocal.value = res.data
    }
  } catch (err) {
    $message.error("获取本地仓库存失败！")
  }
}
const querySaleAmountInOversee=async ()=>{
  try {
    const res = await api.getSaleAmountByStoreType(
      {
        params:{
          type:'海外仓'
        }
      }
    )
    if(res.code === 200) {
      saleAmountInOversee.value = res.data
    }
  } catch (err) {
    $message.error("获取本地仓库存失败！")
  }
}
const querySaleAmountInPlatform=async ()=>{
  try {
    const res = await api.getSaleAmountByStoreType(
      {
        params:{
          type:'平台仓'
        }
      }
    )
    if(res.code === 200) {
      saleAmountInPlatform.value = res.data
    }
  } catch (err) {
    $message.error("获取本地仓库存失败！")
  }
}

const saleMoneyInLocal=ref(0)
const saleMoneyInOversee=ref(0)
const saleMoneyInPlatform=ref(0)
const querySaleMoneyInLocal=async ()=>{
  try {
    const res = await api.getSaleMoneyByStoreType(
      {
        params:{
          type:'本地仓'
        }
      }
    )
    if(res.code === 200) {
      saleMoneyInLocal.value = res.data
    }
  } catch (err) {
    $message.error("获取本地仓库存失败！")
  }
}
const querySaleMoneyInOversee=async ()=>{
  try {
    const res = await api.getSaleMoneyByStoreType(
      {
        params:{
          type:'海外仓'
        }
      }
    )
    if(res.code === 200) {
      saleMoneyInOversee.value = res.data
    }
  } catch (err) {
    $message.error("获取本地仓库存失败！")
  }
}
const querySaleMoneyInPlatform=async ()=>{
  try {
    const res = await api.getSaleMoneyByStoreType(
      {
        params:{
          type:'平台仓'
        }
      }
    )
    if(res.code === 200) {
      saleMoneyInPlatform.value = res.data
    }
  } catch (err) {
    $message.error("获取本地仓库存失败！")
  }
}

//商品销售分析
const saleMoneyByCategoryList=ref([])
const querySaleMoneyByCategory=async ()=>{
  try {
    const res = await api.getSaleMoneyByCategory()
    if(res.code === 200) {
      res.data.map((item)=>{
        saleMoneyByCategoryList.value.push({
          categoryName: item.categoryName,
          saleMoney: item.saleMoney
        })
      })

    }
  } catch (err) {
    $message.error("获取本地仓库存失败！")
  }
}
const updateChartData = () => {
  // 使用map将saleMoneyByCategoryList转换为ECharts所需的格式
  const formattedData =ref([])
  saleMoneyByCategoryList.value.map((item)=>{
    formattedData.value.push({
      name: item.categoryName,
      value: item.saleMoney
    })
  })
  // 直接赋值给option5的data属性
  option5.value.series[0].data = formattedData.value;
  console.log(option5.value.series[0].data)
};
const sortMap=async ()=>{
  try {
    sortSaleMoneyByCategory.value = saleMoneyByCategoryList.value.slice().sort((a, b) => {
      // 根据 saleMoney 降序排序
      return b.saleMoney - a.saleMoney;

    });

  } catch (err) {
    $message.error("获取排序存失败！")
  }
}
const sortSaleMoneyByCategory=ref([])
const sortCategoryName=()=>{
  let length=sortSaleMoneyByCategory.value.length
  if(length>0){
    sortCategory1.value=sortSaleMoneyByCategory.value[0].categoryName
    length-=1
  }
  if(length>0){
    sortCategory2.value=sortSaleMoneyByCategory.value[1].categoryName
    length-=1
  }
  if(length>0){
    sortCategory3.value=sortSaleMoneyByCategory.value[2].categoryName
    length-=1
  }
  if(length>0){
    sortCategory4.value=sortSaleMoneyByCategory.value[3].categoryName
  }
}
const sortSaleMoney=()=>{
  let length=sortSaleMoneyByCategory.value.length
  let sum=0
  let i=0
  for(i;length>i;i++){
    sum=sum+sortSaleMoneyByCategory.value[i].saleMoney
  }
  if(length>0){
    sortMoney1.value=(parseFloat((sortSaleMoneyByCategory.value[0].saleMoney*100/sum).toFixed(2)))+"%"
    sortSaleMoney1.value=sortSaleMoneyByCategory.value[0].saleMoney

    console.log(sortMoney1.value)
    length-=1
  }
  if(length>0){
    sortMoney2.value=(parseFloat((sortSaleMoneyByCategory.value[1].saleMoney*100/sum).toFixed(2)))+"%"
    sortSaleMoney2.value=sortSaleMoneyByCategory.value[1].saleMoney
    length-=1
  }
  if(length>0){
    sortMoney3.value=(parseFloat((sortSaleMoneyByCategory.value[2].saleMoney*100/sum).toFixed(2)))+"%"
    sortSaleMoney3.value=sortSaleMoneyByCategory.value[2].saleMoney
    length-=1
  }
  if(length>0){
    sortMoney4.value=(parseFloat((sortSaleMoneyByCategory.value[3].saleMoney*100/sum).toFixed(2)))+"%"
    sortSaleMoney4.value=sortSaleMoneyByCategory.value[3].saleMoney
  }
}
const sortCategory1=ref(null)
const sortCategory2=ref(null)
const sortCategory3=ref(null)
const sortCategory4=ref(null)
const sortSaleMoney1=ref(null)
const sortSaleMoney2=ref(null)
const sortSaleMoney3=ref(null)
const sortSaleMoney4=ref(null)
const sortMoney1=ref(null)
const sortMoney2=ref(null)
const sortMoney3=ref(null)
const sortMoney4=ref(null)

//店铺销售分析
const shopList=ref([])
const shopSaleMoneyList=ref([])
const getShopsInCustomerOrder=async ()=>{
  try {
    const res = await api.getShopsInCustomerOrder( )
    if(res.code === 200) {
      const existingIds = new Set();
      res.data.forEach((item) => {
        // 检查id是否已经在Set中
        if (!existingIds.has(item.id)) {
          // 如果id不存在，则添加到Set和shopList.value
          existingIds.add(item.id);
          shopList.value.push({
            id: item.id,
            name: item.name,
          });
        }
      });
     // console.log(shopList.value)
    }
  } catch (err) {
    $message.error("获取店铺信息失败！")
  }
}
const queryShopSaleMoneyList = async () => {
  loading.value = true
  try{
    for (let shop of shopList.value){
      const res=await api.getSaleMoneyByShopId({
        params: {
          id:shop.id,
        }
      })
      if(res.code===200)
      {
        shopSaleMoneyList.value.push ({
        id:shop.id,
          name:shop.name,
          saleMoney:res.data,
        });
      }else {
        $message.error(res.message)
      }
    }
   // console.log("获取销售额")
    //console.log(shopSaleMoneyList.value)
  }catch (err){
    $message.error("统计店铺销售额失败！")
  }finally{
    loading.value = false
  }
}
const sortShopList=ref([])
const sortShopSaleMoneyList=async ()=>{
  try {
    sortShopList.value = shopSaleMoneyList.value.slice().sort((a, b) => {
      // 根据 saleMoney 降序排序
      return b.saleMoney - a.saleMoney;
    });

  } catch (err) {
    $message.error("获取排序存失败！")
  }
}
const updateChartData7 = () => {
  // 使用map将saleMoneyByCategoryList转换为ECharts所需的格式
  const formattedData =ref([])
  //console.log("排序后")
  //console.log(sortShopList.value)
  let sum=0
  let i=0
  for(i;length>i;i++){
    sum=sum+formattedData.value[i].saleMoney
  }
  sortShopList.value.map((item)=>{
    formattedData.value.push({
      name: item.name,
      value: item.saleMoney,
    })
  })
  // 直接赋值给option5的data属性
  option7.value.series[0].data = formattedData.value;
  formattedData.value=[]
  sortShopList.value.map((item)=>{
    formattedData.value.push({
      name: item.name,
    })
  })
  const newArray = formattedData.value.map(item => item.name);
};

//订单销售分析
const customerOrderQuantity=ref([])
const queryCustomerOrderQuantity=async()=>{
  try {
    const res = await api.getOrderQuantityByStatus()
    if(res.code === 200) {
      res.data.map((item) => {
        customerOrderQuantity.value.push({
          name:item.status,
          value:item.orderQuantity,
        })
      })
    }else {
      $message.error(res.message)}
   // console.log("customerOrderQuantity:")
    //console.log(customerOrderQuantity.value)
    option2.value.series[0].data = customerOrderQuantity.value;
   // console.log("订单销售情况")
    //console.log(option2.value.series[0].data)
  } catch (err) {
    $message.error("获取订单数量失败！")
  }
}
const orderPriceList=ref([])
const queryOrderPrice=async()=>{
  try {
    const res = await api.getPriceByOrderType({
      params:{
        orderType:"customer_order"
      }
    })
    if(res.code === 200) {
        orderPriceList.value.push({
          name:"客户订单",
          value:res.data,
        })
    }else {
      $message.error(res.message)}
    const res1 = await api.getPriceByOrderType({
      params:{
        orderType:"provider_logistics_order"
      }
    })
    if(res1.code === 200) {
      orderPriceList.value.push({
        name:"物流订单",
        value:res1.data,
      })
    }else {
      $message.error(res1.message)}
    const res2 = await api.getPriceByOrderType({
      params:{
        orderType:"purchase_order"
      }
    })
    if(res2.code === 200) {
      orderPriceList.value.push({
        name:"采购订单",
        value:res2.data,
      })
    }else {
      $message.error(res2.message)}
    console.log("orderPriceList:")
    console.log(orderPriceList.value)
    option3.value.series[0].data = orderPriceList.value;

  } catch (err) {
    $message.error("获取金额失败！")
  }
}


function getLastSevenDays() {
    let days = [];
    let currentDate = new Date();
    for (let i = 0; i < 7; i++) {
        let year = currentDate.getFullYear();
        let month = (currentDate.getMonth() + 1).toString().padStart(2, '0'); // 加 1 并确保两位数字
        let day = currentDate.getDate().toString().padStart(2, '0'); // 确保两位数字
        days.unshift(`${year}-${month}-${day}`);
        currentDate.setDate(currentDate.getDate() - 1);
    }
    return days;
}
const renderOption1 = async () => {
    try{
        await getSaleAmountInWeek()
        await getSaleMoneyInWeek()
        await getSaleProfitInWeek()
        await getTotalCostInWeek()
        await getLogisticsProviderCostInWeek()

        option1.value.series[0].data = saleAmountInWeek.value
        option1.value.series[1].data = saleMoneyInWeek.value
        option1.value.series[2].data = saleProfitInWeek.value
        option1.value.series[3].data = totalCostInWeek.value
        option1.value.series[4].data = logisticsProviderCostInWeek.value
        option1Chart.setOption(option1.value)
    }catch (e) {
        console.log(e)
    }
}
const getSaleAmountInWeek = async () => {
    try {
        const res = await api.getSaleAmountInWeek()
        if(res.code === 200) {
            saleAmountInWeek.value = res.data;
        }
    } catch (err) {
        $message.error("获取销售量失败！")
    }
}
const getSaleMoneyInWeek = async () => {
    try {
        const res = await api.getSaleMoneyInWeek()
        if(res.code === 200) {
            saleMoneyInWeek.value = res.data;
        }
    } catch (err) {
        $message.error("获取销售额失败！")
    }
}
const getSaleProfitInWeek = async () => {
    try {
        const res = await api.getSaleProfitInWeek()
        if(res.code === 200) {
            saleProfitInWeek.value = res.data;
        }
    } catch (err) {
        $message.error("获取销售利润失败！")
    }
}
const getTotalCostInWeek = async () => {
    try {
        const res = await api.getTotalCostInWeek()
        if(res.code === 200) {
            totalCostInWeek.value = res.data;
        }
    } catch (err) {
        $message.error("获取成本价失败！")
    }
}
const getLogisticsProviderCostInWeek = async () => {
    try {
        const res = await api.getLogisticsProviderCostInWeek()
        if(res.code === 200) {
            logisticsProviderCostInWeek.value = res.data;
        }
    } catch (err) {
        $message.error("获取物流订单数失败！")
    }
}

//店铺销售量分析（柱状图）
const allShopList=ref([])
const shopSaleQuantityList=ref([])
const queryAllShopList = async () => {
  loading.value = true
  try {
    const res = await api.findAllShop()
    if (res.code === 200) {
      res.data.map((item) => {
        allShopList.value.push({
          id:item.id,
          name:item.name,
        })
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取店铺信息失败！")
  } finally {
    loading.value = false
  }
}
const queryShopQuantity = async () => {
  loading.value = true
  try{
    for (let shop of allShopList.value){
      const res=await api.getSaleQuantityByShopId({
        params: {
          id:shop.id,
        }
      })
      if(res.code===200)
      {
        shopSaleQuantityList.value.push ({
         name:shop.name,
          value:res.data,
        });
      }else {
        $message.error(res.message)
      }
    }
    console.log("shopSaleQuantity:")
    console.log(shopSaleQuantityList.value)
    option4.value.series[0].data=shopSaleQuantityList.value
    const newArray = shopSaleQuantityList.value.map(item => item.name);
    option4.value.xAxis.data=newArray
    console.log("data=")
    console.log(data)
    console.log("dataAxis=")
    console.log(dataAxis)
  }catch (err){
    $message.error("统计数据失败！")
  }finally{
    loading.value = false
  }
}
function getCurrentFormattedDateTime() {
  var now = new Date();
  var year = now.getFullYear();
// JavaScript中的月份是从0开始的，所以需要加1
  var month = String(now.getMonth() + 1).padStart(2, '0');
  // getDate() 返回的是月份中的日期（1-31）
  var day = String(now.getDate()).padStart(2, '0');
  var hours = String(now.getHours()).padStart(2, '0');
  var minutes = String(now.getMinutes()).padStart(2, '0');
  var seconds = String(now.getSeconds()).padStart(2, '0');
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}
console.log(getCurrentFormattedDateTime()); // 输出类似 "2023-07-19 14:30:45"
onMounted(() => {
    option1Chart = echarts.init(option1Container.value)
    option1Chart.setOption(option1.value)
    renderOption1();

    querySaleAmount()
    querySaleMoney()
    querySaleProfit()
    querySaleCost()
    queryLogisticProviderCost()

    querySaleAmountYesterday()
    querySaleMoneyYesterday()
    querySaleProfitYesterday()
    querySaleCostYesterday()
    queryLogisticProviderCostYesterday()

    queryNationList().then(()=>{
        queryStaticsList()
    })

    queryAmountInLocal()
    queryAmountInPlatform()
    queryAmountInOversee()
    querySaleAmountInLocal()
    querySaleAmountInOversee()
    querySaleAmountInPlatform()
    querySaleMoneyInLocal()
    querySaleMoneyInOversee()
    querySaleMoneyInPlatform()

    querySaleMoneyByCategory().then(()=>{
      updateChartData()
      option5Chart = echarts.init(option5Container.value)
      option5Chart.setOption(option5.value)
      sortMap()
      sortCategoryName()
      sortSaleMoney()
    })

    getShopsInCustomerOrder().then(()=> {
      queryShopSaleMoneyList().then(() => {
        sortShopSaleMoneyList()
        updateChartData7()
        option7Chart = echarts.init(option7Container.value)
        option7Chart.setOption(option7.value)
      })
    })
    queryCustomerOrderQuantity().then(()=>{
      option2Chart = echarts.init(option2Container.value)
      option2Chart.setOption(option2.value)
    })

    queryOrderPrice().then(()=>{
      option3Chart = echarts.init(option3Container.value)
      option3Chart.setOption(option3.value)
    })

    queryAllShopList().then(()=>{
      queryShopQuantity().then(()=>{
        option4Chart = echarts.init(option4Container.value)
        option4Chart.setOption(option4.value)
        option4Chart.on('click', function (params) {
          option4Chart.dispatchAction({
            type: 'data2Zoom',
            startValue: dataAxis[Math.max(params.data2Index - zoomSize / 2, 0)],
            endValue:
              dataAxis[Math.min(params.data2Index + zoomSize / 2, data.length - 1)]
          });
      })

      });
    })

  querySaleAmountList().then(()=>{
    option6Chart = echarts.init(option6Container.value)
    option6Chart.setOption(option6.value)
  })
  })
</script>
<style scoped>
.column-card-left {
    margin-top: 10px;
    margin-left: 20px;
    width: 97%;
    padding-bottom: 20px;
}
.second-column-card {
    margin-top: 20px;
}
.second-column-card-left {
    width: 48%;
}
.second-column-card-right {
    width: 48%;
}
.shadow-card {
    box-shadow: 0 3px 6px 0 rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
    transition: box-shadow 0.3s ease; /* 阴影变化的过渡效果 */
}
/* 当鼠标悬停在卡片上时，可以加深阴影效果以增加交互性 */
.shadow-card:hover {
    box-shadow: 0 3px 10px 0 rgba(0, 0, 0, 0.15);
}
.third-column-card {
    margin-top: 20px;
}
.third-column-card-left {
    width: 40%;
}
.third-column-card-right {
    width: 56%;
}
.fourth-column-card {
    margin-top: 20px;
}
.fourth-column-card-left {
    width: 42%;
}
.fourth-column-card-middle {
    width: 26%;
}
.fourth-column-card-right {
    width: 26%;
}
.button-with-icon {
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中，可以根据需要调整 */
}
.table-with-icon {
    margin-left: 2px;
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: left; /* 水平居中，可以根据需要调整 */
}
.icon-material-symbols {
    font-family: "iconfont" !important;
    font-size: 16px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    margin-right: 5px;
}
.left-button {
    border-top-left-radius: 5px; /* 或者您想要的任何圆角大小 */
    border-bottom-left-radius: 5px;
}

.right-button {
    border-top-right-radius: 5px; /* 或者您想要的任何圆角大小 */
    border-bottom-right-radius: 5px;
}
.fourth-left-right-div {
    display: flex;
    flex-direction: row;
    align-items: center;
    border-radius: 5px;
    padding: 10px 20px;
}
.fourth-left-right-div-left {
    background-color: rgb(240, 245, 254);
    border: 1px solid rgb(148, 187, 255);
}
.fourth-left-right-div-right {
    background-color: rgb(253, 250, 255);
    border: 1px solid rgb(222, 173, 255);
}
.th-left {
    font-weight: bolder;
}
.th-right {
    width: 25%;
    font-weight: bolder;
    font-size: 14px;
    line-height: 22px;
    color: #000000a6;
    align-items: center;
}
.th-right-text{
    font-size: 20px;
    font-weight: 700;
    text-align: left;
}
.align-end {
    align-self: flex-end;
    margin-bottom: 10px; /* 或者根据你的设计调整 */
}

.align-start {
    align-self: flex-start;
    margin-top: 10px; /* 或者根据你的设计调整 */
}
.diagonal-line {
    position: relative;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: repeating-linear-gradient(
            30deg,
            #d9dbde,
            #d9dbde 1px,
            transparent 1px,
            transparent 50%
    );
    pointer-events: none; /* 确保直线不可点击 */
}
.last-line-text {
    font-size: 14px;
    font-weight: 700;
    line-height: 22px;
    margin-bottom: 8px;
    text-transform: capitalize;
    color: #000;
    cursor: pointer;
}
</style>